﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IniParser;
using IniParser.Model;
using Microsoft.AspNet.SignalR.Client;
using SignalR.ChatRoom.Client.UI;
using SignalR_ChatRoom_Server.Model.Entities;

namespace SignalR_ChatRoom_Server.Services
{
    public class ChatService : IChatService
    {
        #region 接口成员
        public event Action<int> UserLoggedIn;
        public event Action<int> UserLoggedOut;
        public event Action<int> UserDisconnected;
        public event Action<int> UserReconnected;
        public event Action<int, Enums.MsgType, string> OnNewMessage;
        public event Action<int, Enums.MsgType, byte[]> OnMewImage;
        public event Action<int> UserTyping;
        #endregion

        private IHubProxy _hubProxy;
        private HubConnection _hubConnection;
        private IniData _data;
        public ChatService()
        {
            var parser = new FileIniDataParser();
            _data = parser.ReadFile("Configs\\settings.ini");
        }

        public async Task ConnectAsync()
        {
            string route = _data["Deploy"]["Route"];
            _hubConnection = new HubConnection(route);
            _hubProxy = _hubConnection.CreateHubProxy("ChatHub");
            _hubProxy.On<int>("UserLogIn", (id) => UserLoggedIn?.Invoke(id));
            _hubProxy.On<int>("UserLogout", (id) => UserLoggedOut?.Invoke(id));
            _hubProxy.On<int>("UserDisConnect", (id) => UserDisconnected?.Invoke(id));
            _hubProxy.On<int>("UserReconnect", (id) => UserReconnected?.Invoke(id));
            _hubProxy.On<int, Enums.MsgType, string>("OnMessageReceive", (id, msgType, msg) => OnNewMessage?.Invoke(id, msgType, msg));
            _hubProxy.On<int, Enums.MsgType, byte[]>("OnImageReceive", (id, msgType, img) => OnMewImage?.Invoke(id, msgType, img));
            _hubProxy.On<int>("UserType", (id) => UserTyping.Invoke(id));
            await _hubConnection.Start();
        }

        public async Task<List<Users>> LoginAsync(int logID, string pwd)
        {
            string key = _data["Encryption"]["Key"];
            string vector = _data["Encryption"]["Vi"];
            string encryptWord = EasyEncryption.DES.Encrypt(pwd,key,vector);
            return await _hubProxy.Invoke<List<Users>>("Login",new Object[] {logID, encryptWord });
        }

        public Task LogoutAsync(int logID)
        {
            throw new NotImplementedException();
        }

        public Task SendMessage(int logID, string msg)
        {
            throw new NotImplementedException();
        }
    }
}
